// appsplus_jinglian/pages/order/order.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_tips:'购票须知',
    canlendshow:false,
    len:1,
    prices:'0.00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      scenic_info:options,
    })
    get_ticket_details(this,options.yid);
    
  },
  show:function(){
    var order_tips = this.data.order_tips;
    wx.showModal({
      title: '预定须知',
      content: order_tips,
      showCancel:false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  select_time:function(e){
    this.setData({
      canlendshow:true
    })
  },
  // 关闭日历
  cancel_canlend:function(e){
    this.setData({
      canlendshow: false
    })
  },
  // 下单
  makeOrder:function(e){
    var that = this;
    var token = wx.getStorageSync('jl_user').token;
    var idCard = this.data.idcard;
    var phone = this.data.userphone;
    var name = this.data.username;
    var order_date = this.data.order_date;
    var len = this.data.len;
    if (!order_date) {
      return app.util.message("请选择游玩日期", false, 'error')
    }
    if (!name) {
     return  app.util.message("请填写姓名", false, 'error')
    }
    if (!phone) {
      return app.util.message("请填写手机号", false, 'error')
    }
    if (!idCard){
      return app.util.message("请填写身份证号",false,'error')
    }
    var nowhour = new Date().getHours(); 
    var nowmin  = new Date().getMinutes();
    var day = new Date().getDay;
    var nowmonth = new Date().getMonth()+1;
    if (this.data.ticket_info.maxOrderHour>0){
      if (parseInt(that.data.day) <= day && that.data.cur_month <= nowmonth) {
        
        if (this.data.ticket_info.maxOrderHour < nowhour) {
          return app.util.message("超过最晚可下单时间", false, 'error')
        }
        if (this.data.ticket_info.maxOrderHour == nowhour && this.data.ticket_info.maxOrderMins < nowmin) {
          return app.util.message("超过最晚可下单时间", false, 'error')
        }
      }
      
    }else{
      if (this.data.day == day){
        return app.util.message("需提前一天购票", false, 'error')
      }
    }
    

    app.util.request({
      url:'entry/wxapp/create_order',
      data:{
        token: token,
        name: name,
        phone	:phone,
        idCard:idCard,
        yicketId: e.currentTarget.dataset.yid,
        addtime: order_date,
        len: len,
        attraction_name: e.currentTarget.dataset.name,
      },
      success:function(e){
        console.log(e)
        var ret = e.data;
        if(ret.status){
         
              // console.log(res)
              console.log(ret.data)
           
                wx.requestPayment({
                  timeStamp: ret.data.timeStamp+'',
                  nonceStr: ret.data.nonceStr+'',
                  package: ret.data.package,
                  signType: ret.data.signType,
                  paySign: ret.data.paySign,
                  success: function (res) {
                    that.pay_finish(ret.data.out_trade_no);
                    wx.navigateTo({
                      url: '../order_record/order_record',
                      success: function(res) {},
                      fail: function(res) {},
                      complete: function(res) {},
                    })
                  },
                  fail: function (res) {
                  }
                })
             
              
         
        }else{
          app.util.message(ret.msg, false, 'error')
  
        }
      }
    })
  },
  // 价格日历
  dateSelectAction: function (e) {
    var that = this;
    var cur_day = e.currentTarget.dataset.idx;
    var price = e.currentTarget.dataset.price;
    if (!price){
      return wx.showToast({
        title: '此日无票！',
      })
    }
    var y = this.data.cur_year;
    var m = this.data.cur_month;
    var d = cur_day + 1;
    if(m<10){
      m = '0'+m 
    }
    if(d<10){
      d = '0'+d
    }
    var order_date = ''+y+m+d;
    this.setData({
      todayIndex: cur_day,
      canlendshow: false,
      order_date: order_date,
      day: d,
      prices: that.data.scenic_info.price
    })
    
    console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}`);
  },

  setNowDate: function () {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate() - 1;
    console.log(`日期：${todayIndex}`)
    console.log(`日期：${date.getDay()}`)
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch,
      todayIndex,
    })
  },
  change_count:function(e){
    var that = this;
    console.log(e.currentTarget.dataset.type)
    var maxlen = this.data.ticket_info.maxOrderLen;
    var minlen = this.data.ticket_info.minOrderLen;
    if (e.currentTarget.dataset.type==0){
      if (this.data.len > minlen){
        var count = this.data.len;
          this.setData({
            len: count-1,
            prices: parseInt(that.data.scenic_info.price) * (count - 1)
          })
      }else{
        return app.util.message("最小预定张数" + minlen+"张", false, 'error');
      }
      
    }else{
      if (this.data.len < maxlen) {
        var count = this.data.len;
        this.setData({
          len: count+1,
          prices: parseInt(that.data.scenic_info.price) * (count + 1)
        })
      } else {
        return app.util.message("最大预定张数" +maxlen+"张", false, 'error');
      }
    }
  },
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    var mindex = month>10?month:('0'+month);
    let days = this.data.calculate[mindex]
    console.log(this.data.calculate)
    // let days = [];

    // const thisMonthDays = this.getThisMonthDays(year, month);

    // for (let i = 1; i <= thisMonthDays; i++) {
    //   days.push(i);
    // }

    this.setData({
      days
    });
  },
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    if (handle === 'prev') {
     
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }
      var mindex = newMonth > 10 ? newMonth : ('0' + newMonth);
      if (this.data.calculate[mindex]) {
        this.calculateDays(newYear, newMonth);
        this.calculateEmptyGrids(newYear, newMonth);

        this.setData({
          cur_year: newYear,
          cur_month: newMonth
        })
      }

      

    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }
      var mindex = newMonth > 10 ? newMonth : ('0' + newMonth);
      if (this.data.calculate[mindex]) {
        this.calculateDays(newYear, newMonth);
        this.calculateEmptyGrids(newYear, newMonth);

        this.setData({
          cur_year: newYear,
          cur_month: newMonth
        })
      }
      
    }
  },
  // 表单输入
  order_input:function(e){
    var that = this;
    console.log(e)
    switch (e.currentTarget.dataset.id){
      case 'name': that.setData({ username: e.detail.value});
        break;
      case 'phone': that.setData({ userphone: e.detail.value });
        break;
      case 'idcard': that.setData({ idcard: e.detail.value });
        break;
    }
    
  },
  pay_finish: function (out_trade_no){
    app.util.request({
      url:"entry/wxapp/orders_with",
      data:{
        token: wx.getStorageSync('jl_user').token,
        out_trade_no: out_trade_no
      },
      success:function(ret){

      }
    })
  }
})

// 获取门票详情
function get_ticket_details(that,id){
  app.util.request({
    url:'entry/wxapp/ticket_details',
    data:{
      ticketNameid:id,
    },
    success:function(res){
      var ret = res.data;
      var s = ret.data.orderNotice;
      var dd = s.replace(/<\/?.+?>/g, "");
      dd = dd.replace(/&nbsp;/ig, '');//去掉&nbsp;
      var dds = dd.replace(/ /g, "");//dds为得到后的内容
      that.setData({
        order_tips: dds,
        ticket_info:ret.data,
        calculate:ret.data.time
      })

      that.setNowDate();
      console.log(res)
    }
  })
}